package org.gd.hellocrypt;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

public class LibUtil {

    public static byte[] sha1_raw(String Param, String Encode) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest SHA = MessageDigest.getInstance("SHA-1");
        SHA.reset();
        SHA.update(Param.getBytes(Encode), 0, Param.length());
        byte[] sha1hash = SHA.digest();
        return sha1hash;
    }

    public static String sha1(String Param, String Encode) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        return bytesToHexStr(sha1_raw(Param, Encode));
    }

    public static String toSHA1(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.reset();
        byte[] buffer = input.getBytes();
        md.update(buffer);
        byte[] digest = md.digest();

        String hexStr = "";
        for (int i = 0; i < digest.length; i++) {
            hexStr += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
        }
        return hexStr;
    }

    public static String getUID() {
        NumberFormat formatter = new DecimalFormat("00");
        Calendar now = Calendar.getInstance();
        String day = formatter.format(now.get(Calendar.DAY_OF_MONTH));
        String month = formatter.format(now.get(Calendar.MONTH));
        String year = String.valueOf(now.get(Calendar.YEAR)).substring(2);
        String second = formatter.format(now.get(Calendar.SECOND));
        String current = String.valueOf(System.currentTimeMillis());
        String res = String.format("%s%s%s%s%s", new Object[]{day, month, year, second, current.substring(current.length() - 4)});
        return res;
    }

    public static String md5(String input) throws NoSuchAlgorithmException {
        String md5 = null;
        StringBuffer code = new StringBuffer();
        java.security.MessageDigest messageDigest = java.security.MessageDigest.getInstance("MD5");
        byte bytes[] = input.getBytes();
        byte digest[] = messageDigest.digest(bytes);
        for (int i = 0; i < digest.length; ++i) {
            code.append(Integer.toHexString(0x0100 + (digest[i] & 0x00FF)).substring(1));
        }
        md5 = code.toString();
        return md5;
    }

    public static String bytesToHexStr(byte[] raw) {
        char[] kDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        int length = raw.length;
        char[] hex = new char[length * 2];
        for (int i = 0; i < length; i++) {
            int value = (raw[i] + 256) % 256;
            int highIndex = value >> 4;
            int lowIndex = value & 0x0f;
            hex[i * 2 + 0] = kDigits[highIndex];
            hex[i * 2 + 1] = kDigits[lowIndex];
        }
        return new String(hex);
    }
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");

    public static final String fillString(char c, int length) {
        char[] res = new char[length];
        Arrays.fill(res, c);
        return String.valueOf(res);
    }

    public static final String fillString(String base, char c, int length) {
        if (base == null) {
            return fillString(c, length);
        }

        if (base.length() >= length) {
            return base;
        }

        char[] res = new char[length - base.length()];
        Arrays.fill(res, c);
        return base + String.valueOf(res);
    }

    public static final String prepare4Charset(String string) {
        return ((string == null) ? null : string.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ').replaceAll("[^\\p{Graph}АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЪЭЮЯЫабвгдежзийклмнопрстуфхцчшщьъэюяыЇЄїєЁё]", " "));
    }

    public static String formatAmount(double d) {
        DecimalFormatSymbols npf = new DecimalFormatSymbols();
        npf.setZeroDigit('0');
        npf.setMinusSign('-');
        npf.setDecimalSeparator('.');
        DecimalFormat nf = new DecimalFormat("###########0.00;-###########0.00", npf);

        return nf.format(d);
    }

    public static Date parseDate(String date, Locale loc) {
        if (loc == null) {
            loc = new Locale("ru");
        }
        DateFormat sdfloc = DateFormat.getDateInstance(3, loc);
        try {
            return sdfloc.parse(date);
        } catch (Exception e) {
            try {
                return sdf.parse(date);
            } catch (Exception e2) {
                System.err.println(" Error in parse date: " + e.getMessage());
            }
        }
        return null;
    }

    public static double parseDouble(String doubles, Locale loc) {
        return Double.parseDouble(doubles);
    }

    public static Date parseExpDate(String exp_date_str) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/yy");
        try {
            return sdf.parse(exp_date_str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String formatExpDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/yy");
        return sdf.format(date);
    }

    public static final String quoteCharacters(String x) {
        x = replace(x, '&', "&amp;");
        x = replace(x, '<', "&lt;");
        x = replace(x, '\r', "&#13;");
        x = replace(x, '>', "&gt;");
        x = replace(x, '"', "&quot;");
        x = replace(x, '\'', "&apos;");
        x = replace(x, '«', "&quot;");
        x = replace(x, '»', "&quot;");
        return x;
    }

    public static String deleteSpecSymbols(String x) {
        x = replace(x, '&', "");
        x = replace(x, '<', "");
        x = replace(x, '\r', "");
        x = replace(x, '>', "");
        x = replace(x, '"', "");
        x = replace(x, '\'', "");
        x = replace(x, '«', "");
        x = replace(x, '»', "");
        x = replace(x, '/', "");
        x = replace(x, '{', "");
        x = replace(x, '}', "");
        x = replace(x, '[', "");
        x = replace(x, ']', "");
        x = replace(x, '(', "");
        x = replace(x, ')', "");
        x = replace(x, '#', "");
        x = replace(x, '$', "");
        x = replace(x, ':', "");
        x = replace(x, ';', "");
        x = replace(x, '!', "");
        x = replace(x, '+', "");
        x = replace(x, '@', "");
        x = replace(x, '$', "");
        x = replace(x, '%', "");
        return x;
    }

    static String replace(String s, char out, String in) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) != out) {
                result.append(s.charAt(i));
            } else {
                result.append(in);
            }
        }
        return result.toString();
    }

    public static String setUkrainianText(String str) {
        if (str != null) {
            String res = str.replaceAll("і", "i");
            res = res.replaceAll("ї", "zzz");
            res = res.replaceAll("І", "I");
            res = res.replaceAll("Ї", "ZZZ");
            res = res.replaceAll("Є", "YYY");
            res = res.replaceAll("є", "yyy");
            return res;
        }
        return str;
    }

    public static String getUkrainianText(String str) {
        if (str != null) {
            String res = str.replaceAll("zzz", "ї");
            res = res.replaceAll("і", "i");
            res = res.replaceAll("ZZZ", "Ї");
            res = res.replaceAll("YYY", "Є");
            res = res.replaceAll("yyy", "є");
            return res;
        }
        return null;
    }

    public static Hashtable convertHashMapToHashtable(HashMap map) {
        Hashtable ht = new Hashtable();
        Set set = map.entrySet();
        Iterator itr = set.iterator();
        while (itr.hasNext()) {
            Map.Entry entry = (Map.Entry) itr.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            if (key == null) {
                key = "" + null;
            }
            if (val == null) {
                val = "" + null;
            }
            ht.put(key, val);
        }
        return ht;
    }

    public static String formatDate(Date date, Locale l) {
        if (date == null) {
            return null;
        }
        if (l != null) {
            SimpleDateFormat ldf = new SimpleDateFormat("dd MMM yyyy,E HH:mm:ss", l);
            Calendar cld = GregorianCalendar.getInstance();
            cld.setTime(date);
            if (cld.get(11) == 0) {
                ldf = new SimpleDateFormat("dd MMM yyyy,E", l);
            }
            return ldf.format(date);
        }
        return sdf.format(date);
    }

    public static final String getEncodedCurrentWeekAndYear() {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(new Date());
        byte WEEK_IN_YEAR = (byte) calendar.get(3);
        byte YEAR_NUM = (byte) (calendar.get(1) - 2004);
        byte[] DHSH = new byte[2];
        DHSH[0] = YEAR_NUM;
        DHSH[1] = WEEK_IN_YEAR;
        return Base32.encode(DHSH);
    }

    public static String getCcyNumCode(String ccy) {
        if (ccy.equalsIgnoreCase("UAH")) {
            return "980";
        }
        if (ccy.equalsIgnoreCase("USD")) {
            return "840";
        }
        if (ccy.equalsIgnoreCase("EUR")) {
            return "978";
        }
        if (ccy.equalsIgnoreCase("RUR")) {
            return "810";
        }
        if (ccy.equalsIgnoreCase("XAU")) {
            return "959";
        }
        return ccy;
    }

    public static String calcSignature2(String data, String pass, String encode) {
        try {
            String rez = toSHA1(pass + data + pass);
            rez = new sun.misc.BASE64Encoder().encode((rez).getBytes());
            return rez;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }
}